package vn.com.pavibook.service;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import vn.com.pavibook.dao.SupportNewsDao;
import vn.com.pavibook.domain.model.SupportNews;
import vn.com.pavibook.model.vo.SupportNewsVO;
import vn.com.pavibook.utils.DataHelper;

@Service
public class SupportNewsServiceImpl implements SupportNewsService {

	@Value("${url.support.news.images}")
	private String URL_ROOT_FOLDER_UPLOAD_SUPPORTNEWS;
	
	@Autowired
	private SupportNewsDao supportNewsDao;
	
	@Override
	public List<SupportNews> getAllSupportNews() {
		return supportNewsDao.getAllSupportNews();
	}

	@Override
	public void save(SupportNews supportNews) {
		supportNewsDao.save(supportNews);
	}

	@Override
	public SupportNews getSupportNewsById(int id) {
		return supportNewsDao.getSupportNewsById(id);
	}

	@Override
	public void deleteSupportNewsById(int id) {
		supportNewsDao.delete(id);
	}

	@Override
	public boolean uploadImages(Model model, SupportNewsVO supportNewsVO,
			HttpServletRequest request) {
		
		CommonsMultipartFile bannerFileUpload = supportNewsVO.getFileSupportNewsUpload();

		String rootUrl = URL_ROOT_FOLDER_UPLOAD_SUPPORTNEWS;
		Date dateCurrentImage = new Date();
		long dateCurrentTimeImage = dateCurrentImage.getTime();
		
		//upload image file
		boolean hasErrorUpload = true;
		if (bannerFileUpload == null || bannerFileUpload.getSize() <= 0) {
			hasErrorUpload = true;
			model.addAttribute("errorUpload", DataHelper.UploadFileStatus.UPLOAD_EMPTY.getCode());
		} else {
			String fileName = bannerFileUpload.getOriginalFilename();
			if(fileName.indexOf(".") < 1){
				hasErrorUpload = true;
				model.addAttribute("errorUpload", DataHelper.UploadFileStatus.UPLOAD_EMPTY.getCode());
			}else{
				String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
				String urlFileBanner = "/support_" + dateCurrentTimeImage +"/news_" + dateCurrentTimeImage + "." + fileType;
				String urlFileBannerFull = rootUrl + urlFileBanner;
				supportNewsVO.setUrl_image(urlFileBanner);
				
				String fileTypeImageList = DataHelper.ImageFile.IMAGE_FILE_TYPE.getCode();
				String maxSizeImageStr = DataHelper.ImageFile.IMAGE_FILE_MAX_LENGTH.getCode();
				long maxSizeImage = Long.parseLong(maxSizeImageStr);
				
				String resultUploadFileBanner = uploadSingleFile(bannerFileUpload, urlFileBannerFull, maxSizeImage, fileTypeImageList);
				
				if (DataHelper.ResultUpload.RESULT_UPLOAD_SUCCESS.getCode().equals(resultUploadFileBanner)) {
					
					hasErrorUpload = false;
					model.addAttribute("errorUpload", DataHelper.UploadFileStatus.UPLOAD_SUCCESS.getCode());
				} else if(DataHelper.ResultUpload.RESULT_UPLOAD_ERROR.getCode().equals(resultUploadFileBanner)){
					model.addAttribute("errorUpload", DataHelper.UploadFileStatus.UPLOAD_FILE_ERROR.getCode());
				} else if(DataHelper.ResultUpload.RESULT_UPLOAD_INCORRECT.getCode().equals(resultUploadFileBanner)){
					model.addAttribute("errorUpload", DataHelper.UploadFileStatus.UPLOAD_FILE_FAILURE_FORMAT.getCode());
				} else if(DataHelper.ResultUpload.RESULT_UPLOAD_LIMIT.getCode().equals(resultUploadFileBanner)){
					model.addAttribute("errorUpload", DataHelper.UploadFileStatus.UPLOAD_FILE_LIMIT.getCode());
				}
			
			}
		}
		
		model.addAttribute("hasErrorUpload", hasErrorUpload);
		if(!hasErrorUpload){
			return true;
		}else{
			return false;
		}
	}
	
	public String uploadSingleFile(CommonsMultipartFile filea, String fullPathFileName, long maxSize,String fileTypeList){
		boolean testType = false;
		if(fileTypeList != null){
			
			//check file type
			String [] fileTypeArray = fileTypeList.split(",");
			String filename = null;
			String fileTypeCurrent = null;
			try{
				filename = filea.getOriginalFilename();
				fileTypeCurrent = filename.substring(filename.lastIndexOf(".")+1);
			}catch (Exception e) {
				e.printStackTrace();
				return DataHelper.ResultUpload.RESULT_UPLOAD_INCORRECT.getCode();
			}
			
			if(fileTypeArray.length > 0){
				for(int i = 0; i < fileTypeArray.length; i++){
					if(fileTypeArray[i].equalsIgnoreCase(fileTypeCurrent)){
						testType = true;
					};
				}
			}
		}else{
			testType = true;
		}
		if(testType){
			if (filea.getSize() > 0 && (filea.getSize() <= maxSize || maxSize == 0)) {
				try {
					File file = new File(fullPathFileName);
					file.mkdirs();
					filea.transferTo(file);
				} catch (Exception e) {
					e.printStackTrace();
					return DataHelper.ResultUpload.RESULT_UPLOAD_ERROR.getCode();
				}
				return DataHelper.ResultUpload.RESULT_UPLOAD_SUCCESS.getCode();
			} else {
				return DataHelper.ResultUpload.RESULT_UPLOAD_LIMIT.getCode();
			}
		}else{
			return DataHelper.ResultUpload.RESULT_UPLOAD_INCORRECT.getCode();
		}
	}
	
	public void copyFile(String fromFile, String toFile){
		try{
			File input = new File(fromFile);
			File output = new File(toFile);
			//output.mkdir();
			FileUtils.copyFile(input, output); 
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
